'use strict'

import axios from 'axios'
import qs from 'qs'
import smCrypto from 'sm-crypto'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// const prodMode = process.env.NODE_ENV === 'production'
const prodMode = true

let _axios

if (prodMode) {
  _axios = ({ url, method, params, data, headers }) => {
    const reqId = new Date().getTime()
    if (!headers) {
      headers = {}
    }
    if (!headers['Content-Type']) {
      headers['Content-Type'] = 'application/json;charset=utf-8'
    }

    let param = params || {}
    if (method !== 'POST' || (params && Object.values(params).length > 0)) {
      headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
    } else {
      param = data || params
    }

    // 客户端当前ip地址
    const cip = window.returnCitySN ? returnCitySN.cip : ''

    url = url.replace('/api', '')

    const publicKey = '044ce5921e29fddd521e811f0ce4dafb429dedca717ad60727000ed45653d2ece866f6ecbc300afdb2138582e3f5a2a3b85db0c81b69e162ced5502f38547c0872'
    const privateKey = '26ec8df70d8d6981ec93489ab7cddc8f96f680918e15037f498f76f5ef8948db'
    const ciperMode = 1

    return new Promise(function (resolve, reject) {
      const dataObj = {
        cip,
        isdMethod: method,
        isdForwardURI: url,
        isdUserAgent: navigator.userAgent,
        isdContentType: headers['Content-Type'],
        bizData: param || {}
      }
      console.info('reqId:' + reqId + ', \nparams:' + JSON.stringify(dataObj))

      const paramData = '04' + smCrypto.sm2.doEncrypt(JSON.stringify(dataObj), publicKey, ciperMode)

      // isd jssdk 参数
      const signurl = 'https://' + urldomaincreatesign
      const gatewayurl = 'https://' + urldomaingateway
      var params = {
        data: paramData
      }
      const appId = 'shyjsfphyl'
      const interfaceId = 'ytmpqshyjstywgjk'
      vaildInterfacefn(appId, interfaceId, JSON.stringify(params), '1', signurl, gatewayurl).then((res) => {
        const decryptData = smCrypto.sm2.doDecrypt(res.substr(2), privateKey, ciperMode)
        decryptData ? resolve(JSON.parse(decryptData)) : reject(decryptData)
      })
    })
  }
} else {
  const config = {
    // baseURL: process.env.BASE_URL || process.env.apiUrl || ''
    timeout: 60 * 1000, // Timeout
    withCredentials: true, // Check cross-site Access-Control
    validateStatus: function (status) {
      return status < 500 // Reject only if the status code is greater than or equal to 500
    },
    // `paramsSerializer` 是一个负责 `params` 序列化的函数
    // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
    paramsSerializer: function (params) {
      return qs.stringify(params, { arrayFormat: 'repeat', skipNulls: true })
    }
  }
  
  _axios = axios.create(config)
  
  _axios.interceptors.request.use(
    function (config) {
      // Do something before request is sent
      return config
    },
    function (error) {
      // Do something with request error
      return Promise.reject(error)
    }
  )
  
  // Add a response interceptor
  _axios.interceptors.response.use(
    function (response) {
      // Do something with response data
      return response.data
    },
    function (error) {
      // Do something with response error
      return Promise.reject(error)
    }
  )
}

export default _axios
